/*
 * @Description: 智能测肤
 * @Author: kanglin
 * @Date: 2018-09-05 13:56:00
 * @Copyright: Created by Panxsoft.
 */
 <style lang="less" scoped rel="stylesheet/less" type="text/less" >
     @import "~src/assets/css/common.less";
    .touch-report {
        // background:linear-gradient(90deg,rgba(208,171,250,1) 0%,rgba(224,153,236,1) 100%);
        padding-bottom: 18 *@rem-per-px;
        .charts-panel{
            padding: 0 20 *@rem-per-px;
        }

        .today-panel__list{
            padding: 24*@rem-per-px 0;
        }
        .today-panel__list__item{
            padding: 24*@rem-per-px 0;
		}

		// .today-panel,
		// .history-panel{
		// 	// padding: 18*@rem-per-px 0;
		// }
		.history-panel__not-empty{
			// padding: 18*@rem-per-px 0 0;
			// margin-top: 18*@rem-per-px;
		}

        .analytics-panel{
            background: #ffffff;
			// padding-top: 28*@rem-per-px;
			margin-top: 40*@rem-per-px;
            margin-left: 20*@rem-per-px;
			margin-right: 20*@rem-per-px;
			position: relative;
		}

		.analytics-panel__header{
			background-image: url('//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/baogao_bgxia_img@2x.png ');
            background-size: 100%;
            background-repeat: no-repeat;
            height: 40* @rem-per-px;
			width: 100%;
			position: absolute;
			top: -40*@rem-per-px;
		}

        .analytics-panel__title{
            // margin-top: 68*@rem-per-px;
            text-align: center;
            height:50*@rem-per-px;
            font-size:36*@rem-per-px;
            font-weight:bold;
            line-height:48*@rem-per-px;
            color:rgba(65,72,83,1);
			margin:0 auto;
			padding-top: 28*@rem-per-px;
        }

        .analytics-panel__position{
            padding: 22*@rem-per-px 0  10*@rem-per-px;
        }

        .analytics-panel__detail{
            padding-top: 28 *@rem-per-px;
            margin-left: 40*@rem-per-px;
            margin-right: 30*@rem-per-px;
            .analytics-panel__detail__item{
               padding-bottom: 56 *@rem-per-px;
            }
            .detail__item__label{
                color: #414853;
                font-size:22*@rem-per-px;
                line-height:29*@rem-per-px;
                font-weight:bold;
            }

            .detail__item__desc{
				font-size:18*@rem-per-px;
				text-align: justify;
                font-weight:400;
                color:rgba(102,102,102,1);
                line-height:28*@rem-per-px;
            }

            .detail__item__progress-bar{
                margin: 20*@rem-per-px 0;
                height: 106*@rem-per-px;
            }

        }

        .generation{
            text-align: center;
            padding: 20*@rem-per-px 0 80*@rem-per-px;
        }
    }

 </style>
<template>

	<div class="touch-report">

		<div>
			<touch-problem
				:problems="touch_problem_data"
				:sex="getSex"/>
		</div>

		<!-- BEGIN: charts-panel -->
		<div
			ref="charts-panel"
			class="charts-panel">
			<data-panel
				:default-mode="defaultDateMode"
				@change="handleSwitchChange">
				<div
					slot="today"
					class="today-panel">
					<ul
						v-if="hasDataToday"
						class="today-panel__list">
						<li
							v-for="(item, index) in positions_analytics_group"
							:key="index"
							class="today-panel__list__item">
							<skin-data-chart
								v-if="item"
								:data="normalizeSkinDataChartProps(item)"
								:label="item.skin_name"/>
						</li >
					</ul>
					<default-empty
						v-else
						:height="default_com_height"
						:tips="$t('report.empty_tips_today')"/>
				</div>

				<div
					slot="history"
					class="history-panel">
					<div
						v-if="hasRecords"
						class="history-panel__not-empty">
						<data-nav
							ref="data-nav"
							:items="nav_items_conf"
							:index="nav_active_index"
							@selected="handleNavChange"/>

						<touch-line-chart
							v-if="position_records.length"
							ref="chart"
							:chart-data="position_records"
							@show="handleSelectDate"/>
						<default-empty
							v-else
							:height="default_com_height-navigation_height"
							:tips="$t('report.empty_tips_history')"/>

					</div>
					<default-empty
						v-else
						:height="default_com_height"
						:tips="$t('report.empty_tips_history')"/>
				</div>

			</data-panel>
		</div>
		<!-- END: charts-panel -->

		<!-- BEGIN: analysis-panel -->
		<div
			v-if="position_records.length>0 && current_position_analytics"
			class="analytics-panel">
			<div class="analytics-panel__header"/>
			<h2 class="analytics-panel__title">
				{{ current_position_analytics.skin_name | upperCase }}{{ $t('report.care_analysis') }}
			</h2>

			<div class="analytics-panel__position">
				<m-slick
					:index="nav_active_index"
					:data="postion_thumbs"
					@change="handleSlickChange"/>
			</div>


			<analysis-data
				:elastic="current_position_analytics.flex"
				:moisture="current_position_analytics.water"
				:oil="current_position_analytics.oil"/>

			<!-- BEGIN: 分析详情 -->
			<ul class="analytics-panel__detail">
				<li
					v-for="(item, index) in current_position_analytics.suggests"
					:key="index"
					class="analytics-panel__detail__item">
					<h3 class="detail__item__label">
						{{ analytics_com_conf[index].title}}
					</h3>

					<div class="detail__item__progress-bar">
						<progress-bar
							:gradient-color="analytics_com_conf[index].progress_gradient_color"
							:unit="analytics_com_conf[index].progress_unit"
							:value="current_position_analytics[analytics_com_conf[index].key]"
							:label="item.title"
							:coordinates="analytics_com_conf[index].progress_coordinates"
							wrapper_color="#eeeeff"/>
					</div>

					<p class="detail__item__desc">
						{{ item.analysis }}
					</p>
				</li>
			</ul>
			<!-- ENG: 分析详情 -->

			<div
				class="generation"
				@click="generateSolution(current_position_analytics)">
				<m-button :loading.sync="is_loading">
					<span v-if="is_loading">{{ $t('report.generating') }}</span>
					<span v-else>{{ $t('report.generate_plan') }}</span>
				</m-button>
			</div>
		</div>
		<!-- END: analysis-panel -->

	</div>

</template>

<script>
import { getComputedStyle } from 'src/utils/utils'; // 公有方法

import skinDataChart from 'src/views/component/skinDataChart';
import touchProblem from 'src/views/component/skin-problem/touchProblem';
import analysisData from 'src/views/component/analysis-data';
import progressBar from 'src/views/component/progressbar';
import MButton from 'src/views/component/m-button';
import { parseQueryString } from 'src/utils/helper';
import { $t, isEnglish } from 'src/locales/index';
import defaultEmpty from './default-empty';
import dataPanel from './data-panel';
import dataNav from './data-nav';
import MSlick from './m-slick';
import touchLineChart from './touchLineChart.vue'; // 折线图
import { toDate } from 'src/utils/utils';

const SKIN_POSITION_MAP = {
	EYE_TAIL: 1, // 眼尾
	CHEEK: 2, // 脸
	NECK: 3, // 颈部
	ARM: 4, // 手
};

const TOUCH_PROBLEM_CONF = {
	EYE_TAIL: { title: $t('report.eye_end'), contents: { unknown: { name: $t('rreport.none') } } },
	CHEEK: { title: $t('report.cheek'), contents: { unknown: { name: $t('report.none') } } },
	NECK: { title: $t('report.neck'), contents: { unknown: { name: $t('report.none') } } },
	ARM: { title: $t('report.arm'), contents: { unknown: { name: $t('report.none') } } },
};

const POSITION_THUMBS = { // 部位轮播图 1=>眼尾EYE_TAIL, 2=> 脸CHEEK, 3=>颈部NECK, 4=> 手ARM, 顺序与是固定的
	FEMALE: {
		EYE_TAIL: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_yanwei146_img@2x.png',
		CHEEK: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_lianjia146_img@2x.png',
		NECK: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_jinbu146_img@2x.png',
		ARM: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_shoubi146_img@2x.png',
	},
	MALE: {
		EYE_TAIL: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_yanwei146man_img@2x.png',
		CHEEK: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_lianjia146man_img@2x.png',
		NECK: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_jinbu146man_img@2x.png',
		ARM: '//gz.bcebos.com/v1/beauty-mirror/wx_system/2.3.9/jiechu_shoubi146man_img@2x.png',
	},
};

const MALE = 1;

export default {
	name: 'TouchReport',
	components: {
		'data-panel': dataPanel,
		'skin-data-chart': skinDataChart,
		'touch-problem': touchProblem,
		'analysis-data': analysisData,
		'm-slick': MSlick,
		'progress-bar': progressBar,
		'm-button': MButton,
		'default-empty': defaultEmpty,
		'data-nav': dataNav,
		'touch-line-chart': touchLineChart,
	},
	filters: {
		upperCase(value) {
			const isString = Object.prototype.toString.call(value) === '[object String]';
			if (isEnglish && isString) {
				return value.substring(0, 1).toUpperCase() + value.substring(1);
			}
			return value;
		},
	},
	props: {
		records: {
			type: Array,
			default() {
				return [];
			},
		},
		generate: {
			type: Function,
			required: true,
		},
		sex: {
			type: Number,
			default() {
				return 2;
			},
		},
	},
	data() {
		return {

			positions_analytics_group: [], // 今天的测肤数据: 1=>眼尾EYE_TAIL, 2=> 脸CHEEK, 3=>颈部NECK, 4=> 手ARM, 顺序

			current_position_analytics: null, // 当前分析内容: 某天某测肤部位的测肤数据: 所有记录->  某部位的记录 -> 某天的分析数据

			position_records: [], // 某部位的测肤记录  所有记录-> 某部位的记录

			// positions_analytics_group: null, // 某天各个部位的分析数据 [{部位},{部位}...]

			analytics_com_conf: [ // 分析组件配置
				{
					title: this.$t('report.water_title'),
					key: 'water',
					progress_unit: '%',
					progress_coordinates: [0, 10, 30, 40, 50, 60, 100],
					progress_gradient_color: [{ color: '#88C8FC', frac: 1 }, { color: '#88C8FC', frac: 0 }],
				},
				{
					title: this.$t('report.touch.oil_title'), // '油分',
					key: 'oil',
					progress_unit: '%',
					progress_coordinates: [0, 10, 15, 18, 25, 30, 50],
					progress_gradient_color: [{ color: '#FCD496', frac: 1 }, { color: '#FCD496', frac: 0 }],
				},
				{
					title: this.$t('report.touch.elastic_title'), // 弹性
					key: 'flex',
					progress_unit: '',
					progress_coordinates: [0, 3, 4, 6, 8, 10],
					progress_gradient_color: [{ color: '#FF889D', frac: 1 }, { color: '#FF889D', frac: 0 }],
				},
			],


			is_loading: false,

			nav_active_index: 0,

			touch_problem_data: TOUCH_PROBLEM_CONF,

			today: null,

			is_today: true,

			default_com_height: 0, // 默认组件高度

			navigation_height: 0,

			defaultDateMode: 'today', // or history

		};
	},
	computed: {
		hasDataToday() {
			return this.positions_analytics_group.length;
		},
		getSex() {
			return this.sex;
		},
		hasRecords() {
			let has_records = false;
			this.records.forEach((item) => {
				if (item.skin_records && item.skin_records.length > 0) {
					has_records = true;
				}
			});
			return has_records;
		},

		postion_thumbs() {
			return [
				this.getSex === MALE ? POSITION_THUMBS.MALE.EYE_TAIL : POSITION_THUMBS.FEMALE.EYE_TAIL,
				this.getSex === MALE ? POSITION_THUMBS.MALE.CHEEK : POSITION_THUMBS.FEMALE.CHEEK,
				this.getSex === MALE ? POSITION_THUMBS.MALE.NECK : POSITION_THUMBS.FEMALE.NECK,
				this.getSex === MALE ? POSITION_THUMBS.MALE.ARM : POSITION_THUMBS.FEMALE.ARM,
			];
		},

		nav_items_conf() {
			return [
				{
					name: this.$t('report.eye_end'),
					thumb: this.getSex === MALE ? POSITION_THUMBS.MALE.EYE_TAIL : POSITION_THUMBS.FEMALE.EYE_TAIL,
					key: SKIN_POSITION_MAP.EYE_TAIL,
				},
				{
					name: this.$t('report.cheek'),
					thumb: this.getSex === MALE ? POSITION_THUMBS.MALE.CHEEK : POSITION_THUMBS.FEMALE.CHEEK,
					key: SKIN_POSITION_MAP.CHEEK,
				},
				{
					name: this.$t('report.neck'),
					thumb: this.getSex === MALE ? POSITION_THUMBS.MALE.NECK : POSITION_THUMBS.FEMALE.NECK,
					key: SKIN_POSITION_MAP.NECK,
				},
				{
					name: this.$t('report.arm'),
					thumb: this.getSex === MALE ? POSITION_THUMBS.MALE.ARM : POSITION_THUMBS.FEMALE.ARM,
					key: SKIN_POSITION_MAP.ARM,
				},
			];
		},
	},
	watch: {
		records() {
			this.init();
		},
	},
	created() {
		this.init();
	},

	mounted() {
		this.default_com_height = this.calculatedefaultComHeight();
		// this.navigation_height = this.calculateNavigationHeight();
	},
	updated() {
		if (!this.navigation_height) {
			this.navigation_height = this.calculateNavigationHeight();
		}
	},
	methods: {

		/**
		 * 初始化默认的数据
		 */
		init() {
			this.today = new Date();
			this.mockToday();
			// 眼尾的测肤记录
			this.position_records = this.findPositionRecordsByKeyValue(this.records, SKIN_POSITION_MAP.EYE_TAIL);
			this.positions_analytics_group = this.findPositionsAnalyticsDataGroup(this.records, this.today);
			this.current_position_analytics = this.positions_analytics_group[0] || null; // 某天某部位分析数据对象
			this.touch_problem_data = this.normalizeTouchProblemProps(this.positions_analytics_group);
			// positions_analytics_group positions_analytics_group
			// 如果今天没有部位数据转到历史
			if (this.positions_analytics_group.length === 0) { //
				this.defaultDateMode = 'history';
				this.is_today = false;
			}
		},

		/**
		 * 模拟今日日期
		 */
		mockToday() {
			const query = parseQueryString();
			if ('today' in query) {
				this.today = query.today ? new Date(query.today) : new Date('2018-04-27');
			}
		},

		/**
		 *  查找某一天当中最新的一组各部位完整的测肤分析数据 (不会返回缺少部位的的数据)
		 * @param {Array} records  全部记录
		 * @param {Array} today  全部记录
		 * @return
		 */
		findPositionsAnalyticsDataGroup(records, today) {
			const position_records = this.findPositionRecordsByKeyValue(records, this.nav_items_conf[0].key);
			const analytics_records = this.takeAnalyticsRecordByDate(position_records, today);
			for (let i = 0; i < analytics_records.length; i += 1) {
				const data_group = this.findAnalyticsDataGroupById(records, analytics_records[i].skin_record_id).filter(item => !!item);
				if (data_group.length === this.nav_items_conf.length) {
					return data_group;
				}
			}
			return [];
		},

		/**
		 * 通过skin_record_id查找各部位的分析数据以数组形式返回
		 * @param {Array} records  全部记录
		 * @param {number} skin_record_id
		 * @return {Array} analytics_data
		 */
		findAnalyticsDataGroupById(records, skin_record_id) {
			return this.nav_items_conf.map((item) => {
				const position_records = this.findPositionRecordsByKeyValue(records, item.key);
				const [analytics_data] = position_records.filter(record => record.skin_record_id === skin_record_id);
				return analytics_data;
			});
		},

		/**
		 *  通过皮肤部位的key值找到部位的记录
		 */
		findPositionRecordsByKeyValue(records, key) {
			const [position_records] = records.filter(item => item && item.key === key);
			return position_records && Array.isArray(position_records.skin_records) ? position_records.skin_records : [];
		},

		/**
		 * 查找部位的测肤数据通过日期
		 * @param {Array} position_records 部位测肤记录
		 * @param {Date|string} date 日期
		 * @return {Object} test_data
		 */
		takeAnalyticsRecordByDate(position_records, date) {
			return position_records.filter((item) => {
				if (! item.created_at) {
          return false
				}

				if (date instanceof Date) {
          this.isSameDay(toDate(item.created_at), date)
        } else {
				  return item.created_at === date;
        }
			}).reverse(); // 时间从后到前
			// return test_data;
		},

		/**
		 *  判断日期是否相同
		 * @param {Date} date_1
		 * @param {Date} date_2
		 * @return {Boolean}
		 */
		isSameDay(date_1, date_2) {
			if (date_1.getDate() !== date_2.getDate()) {
				return false;
			} else if (date_1.getMonth() !== date_2.getMonth()) {
				return false;
			} else if (date_1.getFullYear() !== date_2.getFullYear()) {
				return false;
			}
			return true;
		},

		/**
		 *  判断时间字符是否相等
		 * @param {string} d_1
		 * @param {string} d_2
		 * @return {Boolean}}
		 */
		isDateEqual(d_1, d_2) {
			return d_1 === d_2;
		},

		/**
		 *  处理测肤数据图表组件参数
		 * @param {Object} data 某部位测肤数据
		 * @return {Array}
		 */
		normalizeSkinDataChartProps(data) {
			if (data) {
				const moisture = {
					value: `${Number(data.water).toFixed(1)}%`,
					name: $t('report.water'), // 翻译
				};
				const oil = {
					value: `${Number(data.oil).toFixed(1)}%`,
					name: $t('report.oil'), // 翻译
				};
				const elastic = {
					value: data.flex,
					name: $t('report.elastic'), // 翻译
				};
				return [moisture, oil, elastic];
			}
			return [];
		},

		/**
		 *  处理测肤问题指示图参数
		 */
		normalizeTouchProblemProps(positions) {
			const eye_tail = positions ? positions[0] : null;
			const cheek = positions ? positions[1] : null;
			const neck = positions ? positions[2] : null;
			const arm = positions ? positions[3] : null;
			TOUCH_PROBLEM_CONF.EYE_TAIL.contents = this.collectionProblem(eye_tail);
			TOUCH_PROBLEM_CONF.CHEEK.contents = this.collectionProblem(cheek);
			TOUCH_PROBLEM_CONF.NECK.contents = this.collectionProblem(neck);
			TOUCH_PROBLEM_CONF.ARM.contents = this.collectionProblem(arm);
			return Object.assign({}, TOUCH_PROBLEM_CONF);
		},

		/**
		 *  收集皮肤部位的问题
		 */
		collectionProblem(position_attr) {
			if (position_attr && (position_attr.water || position_attr.oil || position_attr.flex)) {
				const [moisture, oil, elastic] = (position_attr.suggests || []);
				return {
					moisture: {
						name: $t('report.water'),
						problem: moisture.title || $t('report.none'),
					},
					oil: {
						name: $t('report.oil'),
						problem: oil.title || $t('report.none'),
					},
					elastic: {
						name: $t('report.elastic'),
						problem: elastic.title || $t('report.none'),
					},
				};
			}
			return { unknown: { name: $t('report.none'), problem: '' } };
		},


		/**
		 *  轮播图切换的回调
		 * @param {Number} index
		 */
		handleSlickChange(index) {
			this.handleNavChange(index);
		},

		/**
		 * 导航回调
		 */
		handleNavChange(index) {
			if (this.is_today) {
				this.current_position_analytics = this.positions_analytics_group[index];
			} else {
				const { key } = this.nav_items_conf[index];
				this.position_records = this.findPositionRecordsByKeyValue(this.records, key); // 某部位的记录
				if (!Array.isArray(this.positions_records) || this.this.positions_records.length === 0) { // 如果没有部位记录,手动重置测肤问题组件
					this.touch_problem_data = this.normalizeTouchProblemProps([]);
				}
			}
			this.nav_active_index = index;
		},

		/**
		 *  折线图回调
		 * @param {string} date
		 */
		handleSelectDate(date) {
			if (date) {
				const [analysis_data] = this.position_records.filter(item => item.created_at === date);
				this.current_position_analytics = analysis_data; // 某天某部位的分析数据
				this.positions_analytics_group = this.findAnalyticsDataGroupById(this.records, analysis_data.skin_record_id);
				this.touch_problem_data = this.normalizeTouchProblemProps(this.positions_analytics_group);
			}
		},

		handleSwitchChange(is_today) {
			this.is_today = is_today;
			if (is_today) {
				this.positions_analytics_group = this.findPositionsAnalyticsDataGroup(this.records, this.today);
				this.current_position_analytics = this.positions_analytics_group[0] || null; // 某天某部位分析数据对象
				this.touch_problem_data = this.normalizeTouchProblemProps(this.positions_analytics_group);
			}
			// this.nav_active_index = 0;
			this.handleNavChange(0);
		},

		/**
		 * 组装某天最新的分析数据
		 * @param {Date} day
		 * @return {Array} latest_data
		 */
		assembleLatestAnalyticsDataOn(day) {
			return this.records
        .map((item) => {
          const [latest] = this.takeAnalyticsRecordByDate(item.skin_records, day)
            .reverse();
          return latest;
        })
        .filter(item => Boolean(item));
		},

		/**
		 * 生成方案
		 */
		generateSolution(current_position_analytics) {
			// const day = current_position_analytics.created_at.substring(0, 10);
			const options = this.assembleLatestAnalyticsDataOn(current_position_analytics.created_at);

      this.is_loading = true;
			this.generate({
				type: 'touch',
				options,
				active_option: current_position_analytics,
			})
				.then((result) => {
					if (result) {
						this.$router.push({
							path: '/recommend',
							query: { type: 'touch' },
						});
					}
					this.is_loading = false;
				});
		},

		/**
		 * 计算默认组件高度
		 */
		calculatedefaultComHeight() {
			const view_height = document.body.clientHeight;
			const { height, top } = document.querySelector('.panel__header__tile').getBoundingClientRect();

			const padding_bottom = getComputedStyle('.touch-report', 'padding-bottom');
			const dH = view_height - (height + top) - padding_bottom;
			return dH;
		},

		/**
		 * 计算导航的高度
		 */
		calculateNavigationHeight() {
			if (this.$refs['data-nav']) {
				const { height } = this.$refs['data-nav'].$el.getBoundingClientRect();
				return height;
			}
			return 0;
		},
	},
};
</script>
